var concerto = {};

concerto.admin = {
	rootUrl:'',
	geekMode:false,
	postData:function(params) {
		params = $.extend({
			data:{},
			dataType:'text',
			success:function() {
			
			},
			loadingText:'Saving...'
		}, params);
		$.ajax({
			url:concerto.admin.rootUrl + 'admin/?' + params.url,
			type:'POST',
			dataType:params.dataType,
			data:params.data,
			beforeSend:function() {
				torchd.ui.showDialog({
					title:params.loadingText,
					type:'ajax-loader'
				});	
			},
			success:function(response) {
				torchd.ui.closeAllDialogs();
				params.success(response);
			}
		});
	},
	init:function() {
		// Load the start panel or main panel if there's nothing in #main
		if(!$('#main').height()) {
			concerto.admin.loadPanel('home');
		}
		concerto.admin.checkForGeeks();
	},
	toggleGeekMode:function() {
		if(this.geekMode) { // Turn off
			$('.menu-geek-mode').removeClass('enabled');
			this.geekMode = false;
			
		}
		else { // Turn on
			$('.menu-geek-mode').addClass('enabled');
			this.geekMode = true;
			
		}
		concerto.admin.checkForGeeks();
	
	},
	checkForGeeks:function() {
		if(this.geekMode) {
			$('.geek-mode').show();
			torchd.ui.menus[0].menus.Settings.parent('li').show();
			torchd.ui.menus[0].menus.Modules.parent('li').show();
			torchd.ui.menus[0].menus.Developer.parent('li').show();
		}
		else { 
			$('.geek-mode').hide();
			torchd.ui.menus[0].menus.Settings.parent('li').hide();
			torchd.ui.menus[0].menus.Modules.parent('li').hide();
			torchd.ui.menus[0].menus.Developer.parent('li').hide();
		}
	},
	reloadDynamicMenus:function() {
		$.ajax({
			url:concerto.admin.rootUrl + '?view=api&display=content_type',
			dataType:'json',
			beforeSend:function() {
				torchd.ui.closeAllDialogs();
				torchd.ui.showDialog({
					type:'ajax-loader',
					title:'Loading Menus...'
				});
			},
			success:function(response) {
				torchd.ui.menus[0].menus['New'].children('li').remove();
				torchd.ui.menus[0].menus['Manage'].children('li').remove();
				var settingsChildren = torchd.ui.menus[0].menus['Settings'].data('children');
				settingsChildren.configure.find('li').remove();
				
				for(var i=0;i<response.data.length;i++) {
					torchd.ui.menus[0].addMenuItem({
						menu:'New',
						name:'new_'+response.data[i].ct_title.toLowerCase(),
						display:response.data[i].ct_title,
						data:{id:response.data[i].ct_id},
						defaultState:'enabled',
						clickAction:function(li) {
							var data = li.data('data');
							var type = data.id;
							var newWindow = window.open(concerto.admin.rootUrl + '?view=form&form=add_content&type=' + type);
							newWindow.focus();
						}
					});
					torchd.ui.menus[0].addMenuItem({
						menu:'Settings',
						subMenu:'configure',
						name:'configure_' + response.data[i].ct_plural.toLowerCase(),
						display:response.data[i].ct_plural,
						data:{id:response.data[i].ct_id},
						defaultState:'enabled',
						clickAction:function(li) {
							var data = li.data('data');
							var type = data.id;
							concerto.admin.loadPanel('configure', {
								type:type
							});
						}
					});
					torchd.ui.menus[0].addMenuItem({
						menu:'Manage',
						name:'manage_' + response.data[i].ct_plural.toLowerCase(),
						display:response.data[i].ct_plural,
						data:{id:response.data[i].ct_id},
						defaultState:'enabled',
						clickAction:function(li) {
							var data = li.data('data');
							var type = data.id;
							concerto.admin.loadPanel('manage', {
								type:type
							});
						}
					});
				}
				torchd.ui.menus[0].addMenuItem({
					menu:'New',
					name:'separator'
				});
				torchd.ui.menus[0].addMenuItem({
					menu:'Manage',
					name:'separator'
				});
				torchd.ui.menus[0].addMenuItem({
					menu:'Settings',
					subMenu:'configure',
					name:'separator'
				});
				torchd.ui.menus[0].addMenuItem({
					menu:'New',
					name:'user',
					display:'User',
					defaultState:'enabled',
					clickAction:function() {
						var newWindow = window.open(concerto.admin.rootUrl + '?view=form&form=add_user', '_blank');
						newWindow.focus();
					}
				});
				torchd.ui.menus[0].addMenuItem({
					menu:'New',
					name:'content_type',
					display:'Content Type',
					class:'geek-mode',
					defaultState:'enabled',
					clickAction:function() {
						concerto.admin.newContentType();
					}
				});
				
				torchd.ui.menus[0].addMenuItem({
					menu:'Settings',
					subMenu:'configure',
					name:'users',
					display:'Users',
					defaultState:'enabled',
					clickAction:function() {
						concerto.admin.loadPanel('configure_users');
					}
				});
				torchd.ui.menus[0].addMenuItem({
					menu:'Manage',
					name:'users',
					display:'Users',
					defaultState:'enabled',
					clickAction:function() {
						concerto.admin.loadPanel('manage_users');
					}
				});
				torchd.ui.closeAllDialogs();
				concerto.admin.checkForGeeks();
			}
		});
	},
	deleteContentType:function(args) {
		torchd.ui.showDialog({
			type:'confirm',
			title:'Delete Content Type?',
			size:'small',
			message:'Are you sure you want to delete this content type? Note that this will also remove all content, tags, feedback, <br />interactions, relations, and data fields associated with this type. There is no going back from this.',
			onSubmit:function() {
				$.ajax({
					url:concerto.admin.rootUrl + 'admin/?display=configure&type='+args.type+'&mode=ajax-method&method=deleteContentType',
					beforeSend:function() {
						torchd.ui.closeAllDialogs();
						torchd.ui.showDialog({
							title:'Deleting...',
							type:'ajax-loader'
						});
					},
					success:function(response) {
						
						torchd.ui.closeAllDialogs();
						concerto.admin.reloadDynamicMenus();
						concerto.admin.loadPanel('home');
					}
				});
			}
		});
	},
	newContentType:function() {
		torchd.ui.showDialog({
			type:'form',
			title:'New Content Type',
			formElements:{
				formItems:[
					{
						name:'title',
						type:'text',
						data:'varchar',
						fields:[
							{
								name:'plural',
								label:'Plural',
							
							},
							{
								name:'singular',
								label:'Singular',
							
							}
						]
					}
					
				],
				buttons:{
					submit:{
						show:false
					},
					cancel:{
						show:false
					}
				}
			},
			
			onSubmit:function(data) {
				$.ajax({
					url:concerto.admin.rootUrl + 'admin/?display=home&mode=ajax-method&method=newContentType',
					type:'POST',
					dataType:'json',
					data:{
						singular:data[0][1].val,
						plural:data[0][0].val
					},
					beforeSend:function() {
						torchd.ui.closeDialog('New Content Type');
						torchd.ui.showDialog({
							title:'Creating...',
							type:'ajax-loader'
						});
					},
					success:function(response) {
						if(response.id) {
							concerto.admin.reloadDynamicMenus();
							concerto.admin.loadPanel('configure', {type:response.id});
							
						}
						else {
						}
					}
				});
			}
		});
	},
	refreshTable:function(table) {
		var addClass = false;
		table.children('tbody').children('tr').each(function() {
			$(this).removeClass('alternate');
			if(addClass) {
				$(this).addClass('alternate');
				addClass = false;
			}
			else {
				addClass = true;
			}
		});
	},
	saveUsersConfiguration:function() {
		var values = concerto.admin.getFormValues($('#main form'));
		values.update_settings = true;
		
		$.ajax({
			url:concerto.admin.rootUrl + 'admin/?mode=handle-data&display=configure_users',
			data:values,
			type:'POST',
			beforeSend:function() {
				torchd.ui.showDialog({
					title:'Saving...',
					type:'ajax-loader',
					modal:true
				});
			},
			success:function(response) {
				torchd.ui.closeDialog('Saving...');
			}
		});

	},
	saveSystemConfiguration:function() {
		var values = concerto.admin.getFormValues($('#main form'));
		values.update_settings = true;
		
		$.ajax({
			url:concerto.admin.rootUrl + 'admin/?mode=handle-data&display=system_settings',
			data:values,
			type:'POST',
			beforeSend:function() {
				torchd.ui.showDialog({
					title:'Saving...',
					type:'ajax-loader',
					modal:true
				});
			},
			success:function(response) {
				torchd.ui.closeDialog('Saving...');
			}
		});

	},

	saveConfiguration:function(args) {
		var values = concerto.admin.getFormValues($('#main form'));
		
		// Parse permalink options
		var singlePermalinkStructure = [];
		$('#single-permalink-structure').children('li').each(function() {
			if(!$(this).hasClass('permalink-structure-blank')){
			
				singlePermalinkStructure.push({
					name:$(this).attr('data-structure'),
					option:$(this).attr('data-option')
				});
			}
		});
		var browsingPermalinkStructure = [];
		$('#browsing-permalink-structure').children('li').each(function() {
			if(!$(this).hasClass('permalink-structure-blank')) {
			
				browsingPermalinkStructure.push({
					name:$(this).attr('data-structure'),
					option:$(this).attr('data-option')
				});
			}
		});
		
		var tagPermalinkStructure = [];
		$('.tag-group-permalink-structure').each(function() {
			var group = {
				id:$(this).attr('data-group-id'),
				structures:[]
			};
			$(this).children('li').each(function() {
				if(!$(this).hasClass('permalink-structure-blank')) {
				
					group.structures.push({
						name:$(this).attr('data-structure'),
						option:$(this).attr('data-option')
					});
				}
			});
			tagPermalinkStructure.push(group);
		});
		
		values.singlePermalinkStructure = singlePermalinkStructure;
		values.tagPermalinkStructure = tagPermalinkStructure;
		values.browsingPermalinkStructure = browsingPermalinkStructure;
		values.update_settings = true;
		
		
		console.log(values);
		$.ajax({
			url:concerto.admin.rootUrl + 'admin/?mode=handle-data&display=configure&'+$.param(args),
			data:values,
			type:'POST',
			beforeSend:function() {
				torchd.ui.showDialog({
					title:'Saving…',
					type:'ajax-loader',
					modal:true
				});
			},
			success:function(response) {
				console.log(response);
				torchd.ui.closeDialog('Saving…');
			}
		});
		
	},
	loadPanel:function(panel, args) {
		var url = concerto.admin.rootUrl + 'admin/?mode=ajax-content&display='+panel
		var jsonSidebarUrl = concerto.admin.rootUrl + 'admin/?mode=json-sidebar&display='+panel;
		var sidebarUrl = concerto.admin.rootUrl + 'admin/?mode=html-sidebar&display='+panel;
		var titleUrl = concerto.admin.rootUrl + 'admin/?mode=ajax-title&display='+panel;
		if(args) {
			url = url +'&'+$.param(args)
			jsonSidebarUrl = jsonSidebarUrl +'&'+$.param(args);
			sidebarUrl = sidebarUrl +'&'+$.param(args);
			titleUrl = titleUrl + '&'+$.param(args);
		}
		$('#sidebar').html('');
		$('#main').html('');
		$.ajax({
			url:titleUrl,
			success:function(response) {
				$('header#top').html('<h1>' + response + '</h1>');
			}
		});
		if(args && panel == 'update' && args.action == 'update') {
			var title = 'Download Update. Please be patient.';
		}
		else {
			var title = 'Loading Panel…';
		}
		$.ajax({
			url:url,
			beforeSend:function() {
				torchd.ui.showDialog({
					title:title,
					type:'ajax-loader'
				});
			},
			error:function(a,b,c) {
				alert(b);
			},
			success:function(response) {
				torchd.ui.closeAllDialogs();
				$('#main').html(response);
				$('.tooltip').each(function() {
					var html = $(this).parent().children('.tooltip-content').html();
					$(this).torchdTooltip({
						animate:'fade',
						animateSpeed:200,
						html:html
					});
				});
				if(concerto.admin.geekMode) {
					$('.geek-mode').show();
				}
				
			}
		});
		if(panel == 'manage' || panel == 'manage_users' || panel == 'home') {
			$.ajax({
				url:sidebarUrl,
				error:function(a,b,c) {
					alert(b);
				},
				success:function(response) {
					
					$('#sidebar').html(response);

					
				}
			});
			
		}
		else {
			$.ajax({
				url:jsonSidebarUrl,
				dataType:'json',
				error:function(a,b,c) {
					alert(b);
				},
				success:function(response) {
					if(panel == 'content_relations') {
						concerto.admin.initContentRelationsSidebar(response);
					}
					else {
						concerto.admin.loadSidebar(response, args, panel);
					}
					
					
					
				}
			});
		}
		
	},
	initContentRelationsSidebar:function(sidebar) {
		$('#sidebar').html('<ul id="sidebar-buttons"></ul>');
		
		if(sidebar) {
			for(var i=0;i<sidebar.length;i++) {
				
				var li = $('<li/>').addClass('draggable-content-type').attr('data-id', sidebar[i].id).html(sidebar[i].title).appendTo($('#sidebar-buttons'));
			}
		}
		$('<li/>').addClass('panel-submit').html('Save Settings').click(function() {
			var formData = [];
			$('ul#content-relations').children('li').each(function() {
				var relation = {};
				relation.crt_name = $(this).children('h4').children('span').html();
				if($(this).attr('data-id')) relation.crt_id = $(this).attr('data-id');
				// Get type IDs
				var i = 1;
				$(this).children('ul').children('li').each(function() {
					relation['relation_type' + i.toString()] = $(this).attr('data-id');
					i++;
				});
				
				if(i == 4) relation.crt_relation_type = 'three-way';
				else relation.crt_relation_type = 'linear';
				formData.push(relation);
			});
			$.ajax({
				url:concerto.admin.rootUrl + 'admin/?display=content_relations&mode=handle-data',
				data:{
					relations:formData
				},
				type:'POST',
				beforeSend:function() {
					torchd.ui.showDialog({
						title:'Saving...',
						type:'ajax-loader'
					});
				},
				success:function(response) {
					torchd.ui.closeDialog('Saving...');
					
				}
			});
		}).appendTo($('#sidebar-buttons'));
		
		
		$('li.draggable-content-type').draggable({
			helper: "clone",
			tolerance:'pointer'
		});
	},
	loadSidebar:function(sidebar, args, panel) {
		if(!args) args = {};
		$('#sidebar').html('<ul id="sidebar-buttons"></ul>');
		if(sidebar) {
			for(var i=0;i<sidebar.length;i++) {
				var li = $('<li/>').data('id', sidebar[i].sectionID).html(sidebar[i].title + '<span class="right-arrow">&rarr;</span>').click(function() {
					$('#main section').hide();
					$('#sidebar-buttons').children('li').removeClass('current');
					$('section#' + $(this).data('id')).show();
					$(this).addClass('current');
				}).appendTo($('#sidebar-buttons'));
				if(i == 0) {
					li.addClass('current');
				}
				if(sidebar[i].geekMode) {
					li.addClass('geek-mode');
				}	
			}
			concerto.admin.checkForGeeks();
		}
		if(panel == 'configure') 
			$('<li/>').addClass('panel-submit').html('Save Settings').click(function() {
						concerto.admin.saveConfiguration(args);
					}).appendTo($('#sidebar-buttons'));
		else if(panel == 'configure_users') 
			$('<li/>').addClass('panel-submit').html('Save Settings').click(function() {
						concerto.admin.saveUsersConfiguration();
					}).appendTo($('#sidebar-buttons'));
		else if(panel == 'system_settings') 
			$('<li/>').addClass('panel-submit').html('Save Settings').click(function() {
						concerto.admin.saveSystemConfiguration();
					}).appendTo($('#sidebar-buttons'));
		else if(panel == 'code_generator') 
			$('<li/>').addClass('panel-submit').html('Get Code!').click(function() {
				// Get currently open section.
				var section = $('section:visible').find('h3').text();
				switch(section) {
					case 'Generate Content Query':
						var codeParameters = []
						$('section:visible').find('ul.applied-parameters').children('li').each(function() {
							codeParameters.push($(this).data('parameters'));
						});
						var codeParameters = codeParameters.join('&');
						torchd.ui.showDialog({
							type:'custom',
							title:'Generated Code',
							construct:function(dialog) {
								dialog.content.append(
									'<label>initQuery Function</label>' +
									'<input class="code" type="text" readonly="readonly" value="<?php initQuery(\'' + codeParameters + '\'); ?>"/>' +
									'<label>Entire Display Loop</label>' + 
									'<textarea class="code" readonly="readonly">' + 
									'<?php initQuery(\'' + codeParameters + '\'); ?>' + 
									'\n<?php if(hasResults()) : ?>' + 
									'\n\t<?php while(hasResults()) : initResult();?>' +
									'\n\t\tDisplay stuff here' +
									'\n\t<?php endwhile;?>' +
									'\n<?php else : ?>' + 
									'\n\tNo results.' + 
									'\n<?php endif; endQuery();?>' +
									'</textarea>' + 
									'<div class="clearboth"></div>'
								);
							}
						});
						break;
					case 'Generate Users Query':
						var codeParameters = []
						$('section:visible').find('ul.applied-parameters').children('li').each(function() {
							codeParameters.push($(this).data('parameters'));
						});
						var codeParameters = codeParameters.join('&');
						torchd.ui.showDialog({
							type:'custom',
							title:'Generated Code',
							construct:function(dialog) {
								dialog.content.append(
									'<label>initUsersQuery Function</label>' +
									'<input class="code" type="text" readonly="readonly" value="<?php initUsersQuery(\'' + codeParameters + '\'); ?>"/>' +
									'<label>Entire Display Loop</label>' + 
									'<textarea class="code" readonly="readonly">' + 
									'<?php initUsersQuery(\'' + codeParameters + '\'); ?>' + 
									'\n<?php if(hasUsers()) : ?>' + 
									'\n\t<?php while(hasUsers()) : initUser();?>' +
									'\n\t\tDisplay stuff here' +
									'\n\t<?php endwhile;?>' +
									'\n<?php else : ?>' + 
									'\n\tNo results.' + 
									'\n<?php endif; endUsersQuery();?>' +
									'</textarea>' + 
									'<div class="clearboth"></div>'
								);
							}
						});
						break;
						
				}
			}).appendTo($('#sidebar-buttons'));
		if(panel == 'configure') {
			$('<li/>').addClass('panel-delete').html('Delete Content Type').click(function() {
						concerto.admin.deleteContentType(args);
					}).appendTo($('#sidebar-buttons'));
		}
	},
	getFormValues:function(element) {
		var values = {};
		element.find('input,textarea,select').each(function() {
			switch($(this).get(0).tagName) {
				case 'INPUT':
					switch($(this).attr('type')) {
						case 'text':
						case 'hidden':
							values[$(this).attr('name')] = $(this).val();
							break;
						case 'checkbox':
							if($(this).attr('name').search(/\[\]/g) > 0) {
								var name = $(this).attr('name').replace('[]', '');
								if(!values[name]) {
									values[name] = [];
								}
								if($(this).is(':checked')) {
									values[name].push($(this).val());
								}
							}
							else {
								if($(this).is(':checked')) {
									values[$(this).attr('name')] = 1;
								}
								else {
									values[$(this).attr('name')] = 0;
								}
							}
							break;
						case 'radio':
							if($(this).is(':checked')) {
								values[$(this).attr('name')] = $(this).val();
							}
							break;
					}
					break;
				case 'SELECT':
					values[$(this).attr('name')] = $(this).find('option:selected').val();
					break;
				case 'TEXTAREA':
					values[$(this).attr('name')] = $(this).html();
					break;
			}
		});
		return values;
	}
};


